import os

from rest_framework.generics import RetrieveDestroyAPIView, ListCreateAPIView
from rest_framework.permissions import IsAuthenticated

from uploads.models import Upload
from uploads.serializers import UploadSerializer


class UploadView(ListCreateAPIView):
    queryset = Upload.objects.all()
    serializer_class = UploadSerializer
    permission_classes = [IsAuthenticated]
    ordering = ['-create_time']  # 默认排序方式

    def perform_create(self, serializer):
        size = self.request.data.get('file').size  # noqa
        name = self.request.data.get('file').name  # noqad
        type = self.request.data.get('file').content_type  # noqad
        serializer.save(file_name=name, file_size=size, file_type=type, create_user=self.request.user)


class UploadDetailView(RetrieveDestroyAPIView):
    queryset = Upload.objects.all()
    serializer_class = UploadSerializer
    permission_classes = [IsAuthenticated]
    ordering = ['-create_time']  # 默认排序方式

    def perform_destroy(self, instance):
        # 获取文件对象
        file_field = instance.file
        # 先调用父类的 perform_destroy（会触发 delete() 逻辑）
        super().perform_destroy(instance)
        # 如果文件存在，进行物理删除
        if file_field and os.path.exists(file_field.path):
            try:
                os.remove(file_field.path)
            except FileNotFoundError:
                pass  # 文件已被删除，忽略异常
